﻿var mapView = {
	onload: function(e) {
		//GetMap();
		ShowToolbar("");
		window.logEvent(e);
		refreshBuses();
	},
	onunload: function(e) {
		window.logEvent(e);
	},
	onfocus: function(e) {
		window.logEvent(e);
	},
	onblur: function(e) {
		window.logEvent(e);
		stopRefreshingPage();
	},
	onbeforetransition: function(e) {
		window.logEvent(e);
	},
	onaftertransition: function(e) {
		window.logEvent(e);
	}
};

var refreshingView = {
    onload: function(e) {
        ShowToolbar("");
        logEvent(e);
        refreshPage(e.target.id);
    },
    onunload: function(e) {
        logEvent(e);
    },
    onfocus: function(e) {
        window.logEvent(e);
    },
    onblur: function(e) {
        window.logEvent(e);
        stopRefreshingPage();
    },
    onbeforetransition: function(e) {
        window.logEvent(e);
    },
    onaftertransition: function(e) {
        window.logEvent(e);
    }
};

var mainView = {
    onload: function(e) {
        ShowToolbar(pageIdMainMenu);
        SetExecType("");
        window.logEvent(e);
    }
};

//var authenticateView = {
//    onload: function(e) {
//        Authenticate();
//    }
//};

function init()
{
    document.body.addEventListener("InternalServerError", function(event) 
    {
        if ($("#errorPane")) {
            $("#errorPane").html(event.request.responseText);
            $("#errorPane").show();
        }
    }, false);
    
    // Not used
    //Authenticate();
}

//function Authenticate()
//{
//    $.ajax(
//    {
//        async: false,
//        url: "/User/Authenticate",
//        data: {},
//        dataType: "json",
//        success: function(data) 
//        {
//            if(data == true)
//            {
//                $("#login").hide();
//                $("#personal").show();
//            }
//            else
//            {
//                $("#login").show();
//                $("#personal").hide();
//            }
//        },
//        error: function(XMLHttpRequest, textStatus, errorThrown) {
//        handleError(XMLHttpRequest.responseText, errorThrown);
//        }
//    });
//    
//}

var JSON_WEBSERVICES_URL = "http://maxik.etr.eastbanctech.ru:8081/CleverService.svc/json/";

var zoom = 16;
var shapeMinZoomLevel = 14;

var map = null;

var center = { lat: 38.8667590000, lon: -77.0541610000 };
var current = { lat: 38.8667590000, lon: -77.0541610000 };
var radius;

var currentShape = null;

var routeShape = null;
var stopShapes = new Array();
var busShapes = new Array();

var pinPoint = null;
var pinPixel = null;

var refreshIntervalID;

var isAuthenticated = false;

var pageIdMainMenu = "mainMenu";
var pageIdMapView = "myMap";
var currentExecType;

//
// The following lines allow you to attach myView to either
//   1) All views
//   2) All views having class 'panel'
//   3) The view having the id 'main'
//
// Comment or uncomment the lines to test/demonstrate the different
// behaviors
//
//window.iui.views.global = myView;
window.iui.views.byID['myMap'] = mapView;
window.iui.views.byID['MyTrip'] = refreshingView;
window.iui.views.byID['StopArrivals'] = refreshingView;
//window.iui.views.byID['Message'] = authenticateView;
window.iui.views.byID['TrainPredictions'] = refreshingView;
window.iui.views.byID['mainMenu'] = mainView;


function logEvent(e)
{
	console.log("logEvent type: " + e.type + "  target " + e.target.tagName + "#" + e.target.id);
	if (e.type == "beforetransition" || e.type == "aftertransition")
	{
		console.log("  out trans = " + e.out);
	}
	else if (e.type == "beforeinsert") {
		console.log("  fragment = " + e.fragment);
	}
	else if (e.type == "afterinsert") {
		console.log("  node = " + e.insertedNode);
	}
}
	
function GetBusRoute(tripId, stopId)
{
    if (routeShape != null) {
        map.DeleteShape(routeShape);
    }

    $.ajax(
    {
        async: false,
        url: "/Transit/GetBusRouteJSON",
        data: { tripId: tripId, stopId: stopId },
        dataType: "json",
        success: function(data) {
            if (data.length > 0) {
                var points = new Array();
                for (var i = 0; i < data.length; i++) {
                    var p = data[i];
                    points[i] = new VELatLong(p.Latitude, p.Longitude, 0, VEAltitudeMode.RelativeToGround);
                }
                routeShape = new VEShape(VEShapeType.Polyline, points);
                map.AddShape(routeShape);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        handleError(XMLHttpRequest.responseText, errorThrown);
        }
    });
}

var routeLayer = new VEShapeLayer();


function ComputePath(kmlLink) {
    map.DeleteShapeLayer(routeLayer);
    routeLayer = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.ImportXML, kmlLink, routeLayer);
    map.ImportShapeLayerData(veLayerSpec, null, 1);                
}

function GetTrainRoute(color) {
    if (routeShape != null) {
        map.DeleteShape(routeShape);
    }

    $.ajax(
    {
        async: false,
        url: "/Transit/GetTrainRouteJSON",
        data: { color: color },
        dataType: "json",
        success: function(data) {
            if (data.length > 0) {
                var points = new Array();
                for (var i = 0; i < data.length; i++) {
                    var p = data[i];
                    points[i] = new VELatLong(p.Latitude, p.Longitude, 0, VEAltitudeMode.RelativeToGround);
                }
                routeShape = new VEShape(VEShapeType.Polyline, points);
                var vecolor = new VEColor(0, 0, 0, 1);
/**
                switch (color) {
                    case "red": vecolor = new VEColor(195, 9, 8, 1); break;
                    case "green": vecolor = new VEColor(1, 114, 62, 1); break;
                    case "blue": vecolor = new VEColor(3, 93, 149, 1); break;
                    case "orange": vecolor = new VEColor(248, 117, 61, 1); break;
                    case "yellow": vecolor = new VEColor(250, 214, 57, 1); break;
                    default: vecolor = new VEColor(0, 0, 0, 1);
                }
*/
                routeShape.SetLineColor(vecolor);
                map.AddShape(routeShape);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        handleError(XMLHttpRequest.responseText, errorThrown);
        }
    });
}

function GetStops(map)
{
    var result;
                
    if(map.GetZoomLevel() > 12)
    {
        $.ajax(
        {
            async: true,
            url: "/Transit/AreaStopsJSON",
            data: { Lat: map.GetCenter().Latitude, Lon: map.GetCenter().Longitude, Zoom: map.GetZoomLevel(), Width: window.innerWidth, Height: window.innerHeight },
            dataType: "json",
            success: function(data) {

                for (var i = 0; i < stopShapes.length; i++) {
                    map.DeleteShape(stopShapes[i]);
                }

                if (data.length > 0) {

                    stopShapes = new Array();

                    for (var i = 0; i < data.length; i++) {
                        var p = data[i];
                        var stopPosition = new VELatLong(p.Lat, p.Lon);
                        var stopShape = new VEShape(VEShapeType.Pushpin, stopPosition);
                        stopShape.SetCustomIcon("<img src='/images/" + p.Type + ".gif'/>");
                        stopShape.SetMinZoomLevel(shapeMinZoomLevel);
                        if (p.Type == 'Bus') {
                            stopShape.SetMoreInfoURL("/Transit/BusStopShortInfo/?stopId=" + p.StopId + "&lat=" + p.Lat + "&lon=" + p.Lon);
                        } else {
                            stopShape.SetMoreInfoURL("/Transit/TrainStopShortInfo/?stopId=" + p.StopId + "&lat=" + p.Lat + "&lon=" + p.Lon);
                        }
                        map.AddShape(stopShape);
                        stopShapes[i] = stopShape;
                    }
                }

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                handleError(XMLHttpRequest.responseText, errorThrown);
            }
        });
    }
}

function GetBuses(map)
{
    // Show buses only if "Next Transport ?"
    if(currentExecType != 'Next')
    {
        for (var i = 0; i < busShapes.length; i++) {
            map.DeleteShape(busShapes[i]);
        }        
        return;
    }

    var result;                
    if(map.GetZoomLevel() > 12)
    {
/**
            $.getJSON( JSON_WEBSERVICES_URL + "JBuses?lat=" + map.GetCenter().Latitude + "&lon=" + map.GetCenter().Longitude + "&radius=" + radius + "&jsoncallback=?", function(data){
                for (var i = 0; i < busShapes.length; i++) {
                    map.DeleteShape(busShapes[i]);
                }

                if (data.length > 0) {
                    busShapes = new Array();
                    for (var i = 0; i < data.length; i++) {
                        var b = data[i];
                        var busPosition = new VELatLong(b.Latitude, b.Longitude);
                        var busShape = new VEShape(VEShapeType.Pushpin, busPosition);
                        busShape.SetCustomIcon("<img src='/images/bus_small.gif'/>");
                        busShape.SetMoreInfoURL("/Transit/BusShotInfo/?busId=" + b.ID + "&tripId=" + b.TripID + "&lat=" + b.Latitude + "&lon=" + b.Longitude);
                        map.AddShape(busShape);
                        busShapes[i] = busShape;
                    }
                }
            });
*/
        $.ajax(
        {
            async: true,
            url: "/Transit/AreaBusesJSON",
            data: { Lat: map.GetCenter().Latitude, Lon: map.GetCenter().Longitude, Zoom: map.GetZoomLevel(), Width: window.innerWidth, Height: window.innerHeight },
            dataType: "json",
            success: function(data) {
                for (var i = 0; i < busShapes.length; i++) {
                    map.DeleteShape(busShapes[i]);
                }

                if (data.length > 0) {
                    busShapes = new Array();
                    for (var i = 0; i < data.length; i++) {
                        var b = data[i];
                        var busPosition = new VELatLong(b.Latitude, b.Longitude);
                        var busShape = new VEShape(VEShapeType.Pushpin, busPosition);
                        stopShape.SetMinZoomLevel(shapeMinZoomLevel);
                        busShape.SetCustomIcon("<img src='/images/bus_small.gif'/>");
                        busShape.SetMoreInfoURL("/Transit/BusShotInfo/?busId=" + b.ID + "&tripId=" + b.TripID + "&lat=" + b.Latitude + "&lon=" + b.Longitude);
                        map.AddShape(busShape);
                        busShapes[i] = busShape;
                    }
                }

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            handleError(XMLHttpRequest.responseText, errorThrown);
            }
        });
    }
}        

function ChangeMap(e)
{
    jQuery.get("/Transit/SetMap", {Lat: map.GetCenter().Latitude, 
                                                Lon: map.GetCenter().Longitude, 
                                                Zoom: map.GetZoomLevel(), 
                                                Width: window.innerWidth, Height: window.innerHeight}, null, "json");
    calculateRadius(map);
    GetBuses(map);
    GetStops(map);
}


function GetMap() 
{ 
	map = new VEMap('myMap');
	map.SetDashboardSize(VEDashboardSize.Small);
		
	var position = new VELatLong(center.lat, center.lon);
	map.LoadMap(position, zoom, VEMapStyle.Road, false, VEMapMode.Mode2D, true, 1);

    var w = $(document).width();
    var h = $(document).height();    
    map.Resize(w, h);
    $("#myMap").css("width",w + "px");
    $("#myMap").css("height",h + "px");
				
    var currentPosition = new VELatLong(current.lat, current.lon);
	currentShape = new VEShape(VEShapeType.Pushpin, currentPosition);
    currentShape.SetCustomIcon("<img src='/images/person.gif'/>");
    map.AddShape(currentShape);
    
    calculateRadius(map);
    GetBuses(map);
    GetStops(map); 
    
    map.AttachEvent("onclick", ShapeInfo);
    map.AttachEvent("onendzoom", ChangeMap);
    map.AttachEvent("onendpan", ChangeMap);    
}

function refreshBuses() {
    updateBuses();
    refreshIntervalID = setInterval("updateBuses()", 60000);
}

function updateBuses() {
    if(map != null)
    {
        GetBuses(map);
    }
}

function refreshPage(id) {
    updatePage(id);
    refreshIntervalID = setInterval("updatePage()", 60000);
}

function updatePage(id) {
    if (!id)
        id = iui.getSelectedPage().id;
    var url = "/Transit/" + id;
    jQuery.get(url, function(data) 
    {
        if($(data).attr("id") == id)
        {
            $("#" + id).html($(data).html());
        }
        else
        {
            $("#" + id).html(data);
        }
    });
}

function stopRefreshingPage() {
    clearInterval(refreshIntervalID);
}

function closePanes() {
    closePane("errorPane");
    closePane("infoPane");
}

function closePane(id)
{
    $("#" + id).hide();
}

function getQueryVariable(query,variable) {   
  var vars = query.split("&"); 
  for (var i=0;i<vars.length;i++) { 
    var pair = vars[i].split("="); 
    if (pair[0] == variable) { 
      return pair[1]; 
    } 
  } 
  return null;
} 

var latitude;
var longitude;
var latLong;
var height;
var pixel;
var leftVal;
var topVal;

function SetPopupVariebles(url)
{
   latitude = getQueryVariable(url,"lat");
   longitude = getQueryVariable(url,"lon");
   latLong = new VELatLong(latitude, longitude);
   height = $('#eidpopupWrapper').height();           
   pixel = map.LatLongToPixel(latLong);
   //donot know why +5 ?
   leftVal = pixel.x-(25 + 5)+"px";   
   topVal = pixel.y-(height)+"px";              
}

var pointSelectMode;
var startShape;
var finishShape;

function ShapeInfo(e) {

    if (pointSelectMode != null) {
        var loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        SetSession(pointSelectMode, loc.Latitude + '_' + loc.Longitude);
        if (pointSelectMode == 'startPoint') {
            if (startShape != null) {
                map.DeleteShape(startShape);
            }
            startShape = new VEShape(VEShapeType.Pushpin, loc);
            map.AddShape(startShape);
        } else {
            if (finishShape != null) {
                map.DeleteShape(finishShape);
            }
            finishShape = new VEShape(VEShapeType.Pushpin, loc);
            map.AddShape(finishShape)
        }
        pointSelectMode = null;
    }

    if (e.elementID != null) {
        shape = map.GetShapeByID(e.elementID);
        var url = shape.GetMoreInfoURL();
        if (shape.GetMoreInfoURL()) {
            $('#infoPane').show();
            var loading = '<span><img src="/images/loading.gif"/>&nbsp;Loading</span>';
            $("#eidPopupContent").html(loading);
            SetPopupVariebles(url);
            $('#eidpopupWrapper').css({ left: leftVal, top: topVal }).show();

            $.ajax(
            {
                async: true,
                url: shape.GetMoreInfoURL(),
                dataType: "html",
                success: function (data) {
                    $("#eidPopupContent").html(data);
                    SetPopupVariebles(url);
                    $('#eidpopupWrapper').css({ left: leftVal, top: topVal }).show();

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    handleError(XMLHttpRequest.responseText, errorThrown);
                }
            });
        }
    }
}

function GetCurrentLocation()
{
    if (navigator.geolocation) 
    {
        // Get current position
        navigator.geolocation.getCurrentPosition(setCurrentLocation, handleError); // Request live position
    } 
    else
    {
        setCurrentLocation( { coords: { latitude: current.lat, longitude: current.lon}})
    }
}		


function setCurrentLocation(position) 
{
    current = { lat: position.coords.latitude, lon: position.coords.longitude };

    map.DeleteShape(currentShape);
    var currentPosition = new VELatLong(current.lat, current.lon);    
    currentShape = new VEShape(VEShapeType.Pushpin, currentPosition);
    currentShape.SetCustomIcon("<img src='/images/person.gif'/>");
    map.AddShape(currentShape);
    
    jQuery.get("/Transit/SetCurrentPosition", { Lat: current.lat, Lon: current.lon }, null, "json");
}


function mapSetup() {
    if (navigator.geolocation) {
        // Get current position
        navigator.geolocation.getCurrentPosition(createMap, handleError); // Request live position
    } 
    else {

        createMap({ coords: { latitude: center.lat, longitude: center.lon} })
    }
}


function createMap(position) {

    current = { lat: position.coords.latitude, lon: position.coords.longitude };
    center = { lat: position.coords.latitude, lon: position.coords.longitude };
    jQuery.get("/Transit/SetMap", { Lat: center.lat, Lon: center.lon, Zoom: 16, Width: window.innerWidth, Height: window.innerHeight }, null, "json");
    
    GetMap();
}

// Error handlers
function handleError(response, error) {
    $("#errorPane").html(response);
    $("#errorPane").show();
    console.log(response);
}

function touchHandler(event){
    var touches = event.changedTouches,
    first = touches[0],
    type = "";

    switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);
                                                                        
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
} 

function addToFavorite(stop, route, direction, type){
    jQuery.get("/Transit/AddToFavarite", { stopId: stop, routeName: route, directionID: direction, type: type }, function(data) { }, "json");
}

function removeFavorite(stop, route, direction, type) {
    $.ajax({
                async: false,
                url: "/Transit/RemoveFavarite",
                data: { stopId: stop, routeName: route, directionID: direction, type: type },
                dataType: "json",
                success: function(data) {}
            });
    updateMyTripInfo();
}

function showStopDirection(Lat, Lon)
{
     var myOptions = new VERouteOptions();
     myOptions.SetBestMapView = false; // Don't change map view
     myOptions.RouteCallback = myRouteHandler;  // Gets VERoute
     myOptions.RouteMode = VERouteMode.Walking;
     map.GetDirections([new VELatLong(current.lat,current.lon, 0, VEAltitudeMode.RelativeToGround), new VELatLong(Lat,Lon, 0, VEAltitudeMode.RelativeToGround)], myOptions);
     window.location.href = '#_myMap';
}

function myRouteHandler(route)
{
    // Unroll route and populate alert text
    var legs          = route.RouteLegs;
    var turns         = "Turn-by-Turn Directions\n";
    var leg           = null;
    var turnNum       = 0;  // The turn #
    var totalDistance = 0;  // The sum of all leg distances

    // Get intermediate legs
    for(var i = 0; i < legs.length; i++)
    {
        // Get this leg so we don't have to dereference multiple times
        leg = legs[i];  // Leg is a VERouteLeg object

        // Unroll each intermediate leg
        var turn        = null;  // The itinerary leg
        var legDistance = null;  // The distance for this leg

        for(var j = 0; j < leg.Itinerary.Items.length; j ++)
        {
             turnNum++;
             // turn is a VERouteItineraryItem object
             turn = leg.Itinerary.Items[j];  
             turns += turnNum + ":  " + turn.Text;
             legDistance    = turn.Distance;
             totalDistance += legDistance;

             // Round distances to 1/10ths
             // Note that miles is the default
             turns += " (" + legDistance.toFixed(1) + " miles)\n";
        }
    }
    turns += "Total distance:  " + totalDistance.toFixed(1) + " miles\n";

    // Show directions
    //alert(turns);
}

function ShowBusRoute(tripId, stopId) {
    GetBusRoute(tripId, stopId);
    window.location.href = '#_myMap';
}

function ShowTrainRoute(color) {
    GetTrainRoute(color);
    window.location.href = '#_myMap';
}

function calculateRadius(map) {
    topleft = map.GetMapView().TopLeftLatLong;
    bottomright = map.GetMapView().BottomRightLatLong;

    radius = getDistance(topleft, bottomright, true);
}

// Calculate distance between two points specified by latitude/longitude using law of cosines.
function getDistance(p1, p2, miles) {
	p1.Latitude= latLonToRadians(p1.Latitude);
	p1.Longitude= latLonToRadians(p1.Longitude);
	
	p2.Latitude= latLonToRadians(p2.Latitude);
	p2.Longitude= latLonToRadians(p2.Longitude);	var R = 6371; // earth's mean radius in km
	var dLat  = p2.Latitude- p1.Latitude;
	var dLong = p2.Longitude- p1.Longitude;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		Math.cos(p1.Latitude) * Math.cos(p2.Latitude) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var disKm = R * c;
	var disMiles = disKm * 0.6214;	return (miles ? disMiles : disKm);
}

//  convert lat/long in degrees to radians
function latLonToRadians( point ) {
	return point * Math.PI / 180;	
}

// Initialize start page
function initWindow()
{        
    init();            
    mapSetup();
    setInterval("GetCurrentLocation()", 30000);        
    ShowToolbar(pageIdMainMenu);                                            
}

function SelectPage(pageId)
{   
    // Return if the same page                   
    if(iui.getSelectedPage().id == pageId)
    {
        return;
    }
        
    iui.showPageById(pageId);
                  
}

function SetExecType(execType)
{
    currentExecType = execType;    
    
    // Set execution type. Can be "Where am I ?", "Fastes way ?" or "Next Transport ?"
    $.ajax({
                async: false,
                url: "/Transit/SetExecType",
                data: { execType: execType },
                dataType: "json",
                success: function(data) {}
            });    
}

function ShowToolbar(pageId)
{
    if(pageId == pageIdMainMenu)
    {
        $("#topMenu").hide();
    } else {
        $("#topMenu").show();    
    }
}

function onClickAddFavorite(id,type,line,stationCode,destinationCode)
{    
    
    if ($("#" + id).attr("toggled") == 'false')
    {
        addToFavorite(stationCode,line,destinationCode,type);
    } else {
        removeFavorite(stationCode,line,destinationCode,type);
    }
}

function SetSession(key,value) {    
    
    $.ajax({
        async: true,
        url: "/Transit/SetSession",
        data: { key: key, value: value },
        dataType: "json",
        success: function (data) { }
    });
}

function SetStartTime() {
    SetSession('StartTime', $('#eidStartTime')[0].value);
}